import java.io.PrintWriter
import java.io.StringWriter
import java.text.SimpleDateFormat

object Logger {
    private const val DEBUG = 4
    private const val INFO = 3
    private const val WARN = 2
    private const val ERROR = 1

    var logLevel = INFO

    fun d(msg: String?) {
        if (logLevel >= DEBUG) {
            println(formatMsg("D", msg))
        }
    }

    fun d(th: Throwable) {
        if (logLevel >= DEBUG) {
            println(formatMsg("D", formatStackTrace(th)))
        }
    }

    fun i(msg: String?) {
        if (logLevel >= INFO) {
            println(formatMsg("I", msg))
        }
    }

    fun w(msg: String?) {
        if (logLevel >= WARN) {
            System.err.println(formatMsg("W", msg))
        }
    }

    fun e(msg: String?) {
        if (logLevel >= ERROR) {
            System.err.println(formatMsg("E", msg))
        }
    }

    fun e(th: Throwable) {
        if (logLevel >= ERROR) {
            System.err.println(formatMsg("E", formatStackTrace(th)))
        }
    }

    private fun formatStackTrace(th: Throwable): String {
        val sw = StringWriter()
        th.printStackTrace(PrintWriter(sw))
        return sw.toString()
    }

    private val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    private fun formatMsg(level: String, msg: String?): String {
        return "${formatter.format(System.currentTimeMillis())} $level: ${msg.orEmpty()}"
    }
}
